#include <stdio.h>
#include "my_spi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
static uint32_t led_bit[led_num];
// #define SPI_WR_BIT_ORDER    1
spi_device_handle_t spi;
int my_spi1_init(void)
{
    esp_err_t ret;
    spi_bus_config_t buscfg={
        .mosi_io_num = PIN_NUM_MOSI1,                // MOSI信号线发送
        .miso_io_num = -1,                // MISO信号线接收
        .sclk_io_num = PIN_NUM_CLK1,                 // SCLK信号线
        .quadwp_io_num = -1,                        // WP信号线，专用于QSPI的D2
        .quadhd_io_num = -1,                        // HD信号线，专用于QSPI的D3
        // .max_transfer_sz = maxSPIFrameInBytes,                    // 最大传输数据大小64个字节
    };
    //spi总线上设备配置
    spi_device_interface_config_t devcfg={
        .clock_speed_hz = SPI_MASTER_FREQ_10M,      // Clock out at 8 MHz,
        .mode = 0,                                  // SPI mode 0设置在第一个上升沿开始采集
        .spics_io_num = -1,
        .queue_size = 1,                            // 传输队列大小，决定了等待传输数据的数量  
    };
    //Initialize the SPI bus
    ret = spi_bus_initialize(spi_num, &buscfg, spi_dma_channel);//初始化spi总线不支持 SPI0/1
    ESP_ERROR_CHECK(ret);
    ret = spi_bus_add_device(spi_num, &devcfg, &spi);//在总线上添加设备
    ESP_ERROR_CHECK(ret);
    if(ret!=ESP_OK)
    {
        while (1)
        {
           printf("设备没有添加成功");
        }   
    }
    else
        printf("设备添加成功\n");

    return ret;
}


int spi_write(void)
{
    esp_err_t ret;
    spi_transaction_t t;
    memset(&t, 0, sizeof(t));       //Zero out the transaction
    // t.length=sizeof(led_bit)*8;                 //总数据长度.
    t.length=led_num_bit;
    t.tx_buffer=led_bit;               //Data
    t.user=(void*)1;                //邮箱I
    
    printf("jUUUUUUUUUUUUUUUUUUUUUUUU\n");
    ret=spi_device_polling_transmit(spi, &t);  //Transmit!启动一个新任务发送轮询任务
    assert(ret==ESP_OK);            //Should have had no issues.
    return ret;

}
void my_led_open(int ledsize) 
{
    uint8_t w = 0xe1;
    uint8_t r = 0xff;
    uint8_t g = 0xff;
    uint8_t b = 0;
    uint32_t my_led_data = r<<24 | g<<16 | b<<8 | 0xe1;
    uint32_t my_led_data1 = w<<24 | b<<16 | g<<8 | r;
    // led_bit[0] = 0;
    for (uint32_t i=1; i<ledsize+1; i++) 
    {
        led_bit[i] = my_led_data;
    }
    // led_bit[ledsize+1]=my_led_data1;
    // for (uint32_t i=ledsize+1; i<led_num; i++) 
    // {
    //     led_bit[i] = 0;
    // }
    // led_bit[led_num]=0;
    spi_write();
    for (int i = 0;i<led_num ; i++)
    {
        vTaskDelay(1);
        printf("%d:%x\n",i,led_bit[i]);
        /* code */
    }

}
void my_led_bit_int(void)
{
    led_bit[0]=0;
    for (uint32_t i=1; i<led_num; i++) 
    {
        led_bit[i] = 0xe0e0e0e0;
    }
    led_bit[led_num-1]=0xffffffff;
    spi_write();
}
